<script setup lang="ts">
import { useRouter } from 'vue-router';
import { ref, onBeforeMount, inject } from 'vue';
import { useStore } from '../../stores';
import { getNewAvatar } from '../../utils/api'
import axios from '../../plugins/axiosInstance'
import { popMessage, popMessageKey, switchPersonCenterShowKey } from '@/type';
import VuePictureCropper, { cropper } from 'vue-picture-cropper'
import { storeToRefs } from 'pinia';
const router = useRouter()
const popMessage = inject(popMessageKey) as popMessage
const store = useStore()
const BaseUrl = store.getBaseUrl()
const close = inject(switchPersonCenterShowKey) as () => void;
/**
 * 用户原本的头像 / 上传的图片 File格式 
 */
const image = ref()
/**
 * 裁剪后的图片
 */
const reviewImage = ref('')
const imageUrl = storeToRefs(store).getUserAvatar
let editInfo = store.getUserInfo
let originInfo = {
    name: editInfo.name,
    introduce: editInfo.introduce,
    avatar: editInfo.avatar,
    id: editInfo.id
}
const isImageEdit = ref(false);
onBeforeMount(() => {
    getNewImage()
    console.log("信息编辑");
})
const getNewImage = () => {
    getNewAvatar().then(res => {
        editInfo.avatar = res.data.data
        if (res.data.code == 1) {
            console.log(`获取用户头像${res.data.data}`);
            axios({
                url: `/common/download?url=image/${res.data.data}`,
                method: 'get',
                responseType: 'blob',
            }).then((res) => {
                image.value = URL.createObjectURL(res.data);
            })
        }
    })
}

const backToList = () => {
    if (isImageEdit.value) {
        isImageEdit.value = false;
    }
}
const toImageEdit = () => {
    isImageEdit.value = !isImageEdit.value;
}
const choseFile = (e: any) => {
    let file = e.target.files[0];
    image.value = URL.createObjectURL(file);
}
const getEditedImg = () => {
    reviewImage.value = cropper?.getDataURL() as string
}
/**
 * 上传用户用户头像
 */
const save = () => {
    const formdata = new FormData()
    cropper?.getBlob().then((res: any) => {
        formdata.append('file', res as Blob)
        axios({
            url: `/common/upload`,
            method: 'post',
            headers: {
                "Content-Type": 'multipart/form-data'
            },
            params: {
                fileType: 'image',
                format: res?.type.split('/')[1]
            },
            data: formdata
        }).then((res) => {
            if (res.data.code === 1) {
                const url = res.data.data
                axios({
                    url: `/user/updateAvatar`,
                    method: 'post',
                    params: {
                        avatar: url
                    }
                }).then(res => {
                    if (res.data.code === 1) {
                        popMessage('成功保存', 'success')
                        store.updateUserAvatar(url)
                        getNewImage()
                    }
                })
            }
        })
    })
}
const infoSave = () => {
    if (originInfo.name == editInfo.name && originInfo.introduce == editInfo.introduce) {
        backToPersonCenter()
    } else {
        axios({
            url: '/user/updateUserInfo', method: 'post', params: {
                introduce: editInfo.introduce,
                nickName: editInfo.name
            }
        }).then(res => {
            if (res.data.code == 1) {
                store.setUserInfoIntro(editInfo.introduce as string)
                store.setUserInfoName(editInfo.name)
                popMessage('保存成功', 'success');
            } else {
                popMessage('保存失败', 'error');
            }
        })
    }
}
const backToPersonCenter = () => {
    close()
    router.back()
}

</script>
<template>
    <div class="content">
        <div class="navigation">
            <template v-if="!isImageEdit">
                <p class="arrow">></p>
                <p class="thisPage">个人设置</p>
            </template>
            <template v-else>
                <h2 class="editTitle">编辑个人资料</h2>
            </template>
        </div>
        <div class="info" v-if="!isImageEdit">
            <form class="musicList">
                <div class="item">
                    <label for="title">昵称</label>
                    <input id="title" type="text" placeholder="昵称" v-model="editInfo.name">
                </div>
                <div class="intro">
                    <label for="description">介绍</label>
                    <textarea id="description" type="text" placeholder="介绍" v-model="editInfo.introduce" />
                </div>
            </form>
            <!-- 专辑图片编辑 -->
            <div class="imgEdit">
                <div class="img" :style="{ backgroundImage: `url(${BaseUrl + '/static/image/' + imageUrl})` }">
                    <div class="mask">
                        <p @click="toImageEdit">更换头像</p>
                    </div>
                </div>
            </div>
        </div>
        <div class="func" v-if="!isImageEdit">
            <span @click="infoSave">保存</span>
            <span @click="backToPersonCenter">返回</span>
        </div>
        <div class="imageEdit" v-else>
            <div class="top">
                <label for="image">上传文件</label>
                <input @change="choseFile" type="file" id="image" accept="image/png, image/jpeg" style="display: none;" />
                <span class="tips">支持jpg、png、bmp格式的图片，且文件小于5M</span>
                <div class="imageEditBox">
                    <div class="imgEditor">
                        <VuePictureCropper :box-style="{
                            width: '100%',
                            height: '100%',
                        }" :img="image" :options="{ viewMode: 1, aspectRatio: 1 / 1 }" @ready="getEditedImg"
                            @cropmove="getEditedImg" @zoom="getEditedImg" />
                    </div>
                    <div class="rightView">
                        <span class="text title">歌单封面预览</span>
                        <div class="view">
                            <img :src="reviewImage" class="largeView">
                            <span class="text">大尺寸头像(200x200像素)</span>
                        </div>
                        <div class="view">
                            <img :src="reviewImage" class="smallView">
                            <span class="text">小尺寸头像预览(40x40像素)</span>
                        </div>
                    </div>
                </div>
                <div class="buttonList">
                    <span @click="save">保存</span>
                    <span @click="backToList">返回</span>
                </div>
            </div>
        </div>

    </div>
</template>
<style scoped lang="css">
.item label,
.intro label {
    margin-right: 35px;
}

.editTitle {
    margin: 0;
    font-size: 24px;
    font-weight: normal;
}

.rightView {
    margin-left: 40px;
    padding-top: 5px;
}

.text:nth-child(n+2) {
    color: #999;
}

.text {
    font-size: 12px;
}

.view {
    display: flex;
    flex-direction: column;
    margin-top: 10px;
    margin-bottom: 10px;
}

.smallView {
    width: var(--music-image-small-size);
    height: var(--music-image-small-size);
    margin-bottom: 5px;
}

.largeView {
    width: var(--music-list-image-size);
    height: var(--music-list-image-size);
    margin-bottom: 5px;

}

.imgEditor {
    padding: 0 40px 0 0;
    border-right: 1px solid #cbcbcb;
    height: 324px;
    width: 324px;
}

.imageEditBox {
    margin-top: 30px;
    display: flex;
}



.tips {
    font-size: 12px;
    color: #999;
}



.top {
    margin-top: 35px;
}



.mask p {
    margin: 0;
    cursor: pointer;
    text-align: center;
    font-size: 12px;
    color: white;
    height: 25px;
    line-height: 25px;
}

.mask {
    position: absolute;
    bottom: 0;
    background-color: rgba(33, 33, 33, 0.6);
    height: 25px;
    width: var(--music-list-img-size);
    z-index: 9999;
}

.content {
    height: 95vh;
    padding: 0 50px;
}

.buttonList {
    margin-top: 30px;
}

.buttonList span,
.func span,
.top label {
    background-color: #f6f6f6;
    padding: 6px 20px;
    margin-right: 20px;
    border: 1px solid #ccc;
    border-radius: 5px;
    cursor: pointer;
}

.func {
    margin-left: 52px;
    margin-top: 45px;
}

.item label {
    font-size: 12px;
}

.intro {
    display: flex;
    margin-top: 50px;
}

.intro label {
    font-size: 12px;
}

.item {
    display: flex;
    align-items: center;
}

#title {
    width: 290px;
    text-indent: 5px;
}

#description {
    width: 290px;
    height: 100px;
    text-indent: 5px;
    resize: none;
}

.musicList {
    flex: 4;
}

.imgEdit {
    flex: 4;
    display: flex;
    justify-content: center;
}

.imgEdit .img {
    position: relative;
    height: var(--music-list-img-size);
    width: var(--music-list-img-size);
    background: round;
}

.info {
    display: flex;
    margin-top: 20px;

}

.thisPage {
    margin: 0;
    font-size: 14px;
    font-weight: 600;
    margin-left: 10px;
}

.arrow {
    margin: 0;
    font-size: 14px;
}

.navigation {
    display: flex;
    padding-top: 40px;
    padding-bottom: 15px;
    border-bottom: 1px solid #cbcbcb;
    align-items: center;

}

.navigation .back {
    color: var(--blue-style);
    cursor: pointer;
    font-size: 12px;
    margin-right: 10px;
    margin-top: 0;
    margin-bottom: 0;
}
</style>